package com.breeze.components.limiter.aop;

import cn.hutool.core.util.ArrayUtil;
import com.breeze.components.core.constant.GlobalConstants;
import com.breeze.components.core.exception.CommonException;
import com.breeze.components.core.util.web.RequestContextUtil;
import com.breeze.components.limiter.anno.RateLimit;
import com.breeze.components.limiter.enums.CacheType;
import com.breeze.components.limiter.enums.LimitType;
import com.breeze.components.limiter.implementation.MapRateLimitChecker;
import com.breeze.components.limiter.implementation.RedisRateLimitChecker;
import com.breeze.components.redis.util.RedissonUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.ParserContext;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

/**
 * 限流处理
 *
 * @author breeze
 */
@Slf4j
@Aspect
public class RateLimiterAspect {

  /** 定义spel表达式解析器 */
  private final ExpressionParser parser = new SpelExpressionParser();

  /** 定义spel解析模版 */
  private final ParserContext parserContext = new TemplateParserContext();

  /** 定义spel上下文对象进行解析 */
  private final EvaluationContext context = new StandardEvaluationContext();

  /** 方法参数解析器 */
  private final ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();

  @Resource private RedisRateLimitChecker redisRateLimitChecker;

  @Resource private MapRateLimitChecker mapRateLimitChecker;

  @Before("@annotation(rateLimit)")
  public void doBefore(JoinPoint point, RateLimit rateLimit) throws Throwable {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    log.info("当前限流方法:{}", method.toGenericString());
    String combineKey = getCombineKey(rateLimit, point);
    switch (rateLimit.cacheType()) {
      case Map:
        mapRateLimitChecker.check(rateLimit, combineKey);
        return;
      case REDIS:
      default:
        redisRateLimitChecker.check(rateLimit, combineKey);
    }
  }

  public String getCombineKey(RateLimit rateLimit, JoinPoint point) {
    String key = rateLimit.key();
    // 获取方法(通过方法签名来获取)
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();
    // 判断是否是spel格式
    if (StringUtils.containsAny(key, "#")) {
      // 获取参数值
      Object[] args = point.getArgs();
      // 获取方法上参数的名称
      String[] parameterNames = pnd.getParameterNames(method);
      if (ArrayUtil.isEmpty(parameterNames)) {
        throw new CommonException("限流key解析异常!请联系管理员!");
      }
      for (int i = 0; i < parameterNames.length; i++) {
        context.setVariable(parameterNames[i], args[i]);
      }
      // 解析返回给key
      try {
        Expression expression;
        if (StringUtils.startsWith(key, parserContext.getExpressionPrefix())
            && StringUtils.endsWith(key, parserContext.getExpressionSuffix())) {
          expression = parser.parseExpression(key, parserContext);
        } else {
          expression = parser.parseExpression(key);
        }
        key = expression.getValue(context, String.class) + ":";
      } catch (Exception e) {
        throw new CommonException("限流key解析异常!请联系管理员!");
      }
    }
    StringBuilder stringBuffer = new StringBuilder(GlobalConstants.RATE_LIMIT_KEY);
    stringBuffer
        .append(
            RequestContextUtil.getRequest()
                .map(HttpServletRequest::getRequestURI)
                .orElseThrow(() -> new CommonException("限流httpRequest获取异常!")))
        .append(":");
    if (rateLimit.limitType() == LimitType.IP) {
      // 获取请求ip
      stringBuffer.append(RequestContextUtil.getClientIp()).append(":");
    } else if (rateLimit.limitType() == LimitType.CLUSTER) {
      if (rateLimit.cacheType().equals(CacheType.Map)) {
        throw new CommonException("限流集群模式不支持Map缓存!");
      }
      // 获取客户端实例id
      stringBuffer.append(RedissonUtil.getClient().getId()).append(":");
    }
    return stringBuffer.append(key).toString();
  }
}
